package classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 自定义 网络类加载器
 *
 * @author dingwen
 * @date 2021/08/29
 */
public class MyURLClassloader extends ClassLoader {
    private String url;

    public MyURLClassloader(ClassLoader parent, String url) {
        super(parent);
        this.url = url;
    }

    public MyURLClassloader(String url) {
        this.url = url;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            // 把类名称转为目录
            String path = url + "/" + name.replace(".", "/") + ".class";
            URL url = new URL(path);
            // 构建输入流
            InputStream inputStream = url.openStream();
            // 构建输出流
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(buf)) != -1) {
                byteArrayOutputStream.write(buf, 0, len);
            }
            byte[] data = byteArrayOutputStream.toByteArray();

            inputStream.close();
            byteArrayOutputStream.close();
            return defineClass(name, data, 0, data.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        MyURLClassloader myURLClassloader = new MyURLClassloader("http://localhost:8080/examples");
        Class<?> clazz = myURLClassloader.findClass("classloader.URLClassLoaderDemo");
        clazz.newInstance();
        //URLClassLoaderDemo new instance
    }
}
